package com.magic.time;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.magic.entity.game.Game;
import com.magic.repository.IGameRepository;
import com.magic.websocket.handle.DefaultWebSocketHander;

/**
 * ClassName: CountDown <br/>
 * Function: 时间倒计时. <br/>
 * date: 2018年10月27日 上午10:04:03 <br/>
 * 
 * @author lishuai11
 * @version
 * @since JDK 1.8
 */
@Component
public class CountDown {

	private static final Logger logger = LoggerFactory.getLogger(CountDown.class);

	@Autowired
	IGameRepository gameRepository;

	private static Map<Integer, Long> mapId = Maps.newConcurrentMap();

	private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");

	public static void addMapId(Game game) {
		mapId.put(game.getGameId(), (long) (game.getHandleTime() * 60));
	}

	public static Map<Integer, Long> getMapId() {
		return mapId;
	}

	public static void updateMapId(Game game) {
		mapId.put(game.getGameId(), (long) (game.getHandleTime() * 60 - 1));
	}

	@PostConstruct
	private void init() {
		List<Game> games = (List<Game>) gameRepository.findByEnd(false);
		if (games != null && !games.isEmpty()) {
			for (Game game : games) {
				mapId.put(game.getGameId(), (long) (game.getHandleTime() * 60));
			}
		}

	}

	@Scheduled(fixedDelay = 1000)
	public void timeCount() {
		if (!mapId.isEmpty()) {
			long time;
			Game game;
			Map<Integer, Long> indexMap = Maps.newHashMap();
			indexMap.putAll(mapId);
			for (Entry<Integer, Long> entry : indexMap.entrySet()) {
				time = entry.getValue();
				time--;
				if (time < 0) {
					mapId.remove(entry.getKey());
					game = gameRepository.findOne(entry.getKey());
					game.setEnd(true);
					gameRepository.save(game);
				} else {
					mapId.put(entry.getKey(), time);
				}
			}
		}
	}

	@Scheduled(fixedDelay = 1000)
	public void sendTime() {
		try {
			simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
			if (!mapId.isEmpty()) {
				String string;
				JSONObject jsonObject;
				for (Entry<Integer, Long> entry : mapId.entrySet()) {
					string = simpleDateFormat.format(new Date(entry.getValue() * 1000));
					jsonObject = new JSONObject();
					jsonObject.put("gameId", entry.getKey());
					jsonObject.put("time", string);
					jsonObject.put("type", "time");
					DefaultWebSocketHander.sendMessageToGame(jsonObject.toJSONString());
				}
			}
		} catch (Exception e) {
			logger.error("CountDown.sendTime()方法异常{}:{}", e.getMessage(), e);
		}
	}

}
